package com.villaday.idf.activity3;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.pop.TipsPop;
import com.villaday.idf.custom.pop.TipsUseDBPop;
import com.villaday.idf.model3.FaPiaoconfigurationsEntity;
import com.villaday.idf.model3.Orders_invoice;
import com.villaday.idf.model3.Orders_invoiceEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DbFaPiaoTitleUtils;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.StatusBarUtils;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import razerdp.basepopup.BasePopupWindow;

/*
 *发票申请
 *
 * */
public class InvoiceApplicationActivity extends BaseActivity {


    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_type1)
    TextView tvType1;
    @BindView(R.id.rb_lvyoufei)
    RadioButton rbLvyoufei;
    @BindView(R.id.rb_zhusufei)
    RadioButton rbZhusufei;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.rb_geren)
    RadioButton rbGeren;
    @BindView(R.id.rb_qiye)
    RadioButton rbQiye;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.img_check)
    ImageView imgCheck;

    @BindView(R.id.ll_title)
    LinearLayout ll_title;

    @BindView(R.id.rg_content)
    RadioGroup rgContent;

    @BindView(R.id.rg_type)
    RadioGroup rgType;
    private Gson gson = new GsonBuilder().create();


    private boolean mIsSoftKeyBoardShowing = false;
    private TipsUseDBPop tipsUseDBPop;
    private String orderNo;
    private LoadingDialog loadingDialog;

    @Override
    protected int getViewResId() {
        return R.layout.activity_invoice_application;
    }

    @Override
    protected void init() {
        orderNo = getIntent().getStringExtra("OrderNo");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            StatusBarUtils.setStatusBarLightMode(this, Color.parseColor("#FFF7F9FB"));
        ToolBarUtil.initToolBar(toolbarText, "发票申请", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        etTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tipsUseDBPop = new TipsUseDBPop(InvoiceApplicationActivity.this, InvoiceApplicationActivity.this, etTitle.getText().toString());
                    tipsUseDBPop.showPopupWindow();
                    tipsUseDBPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            etTitle.clearFocus();
                        }
                    });
                } else {
                    if (tipsUseDBPop != null) {
                        tipsUseDBPop.dismiss();
                    }

                }
            }
        });


        //监听视图树的布局改变(弹出/隐藏软键盘会触发)
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new KeyboardOnGlobalChangeListener());

        mRxManager.on("poptextchange", new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                etTitle.setText(s);
            }
        });

        mRxManager.on("taxpayerNumber", new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                try{etNum.setText(s);}catch (Exception e){

                }

            }
        });

    }

    @OnClick({R.id.rb_lvyoufei, R.id.rb_zhusufei, R.id.rb_geren, R.id.rb_qiye, R.id.img_check, R.id.tv_xuzhi, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_lvyoufei:
                break;
            case R.id.rb_zhusufei:
                break;
            case R.id.rb_geren:
                break;
            case R.id.rb_qiye:
                break;
            case R.id.img_check:
                imgCheck.setSelected(!imgCheck.isSelected());
                break;
            case R.id.tv_xuzhi:
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                HashMap<String, String> map = new HashMap<>();
                map.put("key", "invoice_notice");
                OkHttpUtil.getJSON(this, Constant.URL.faPiaoconfigurations, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        dismissLoading();
                        if (json != null) {
                            LogeUtil.e("faPiaoconfigurations", json);
                            FaPiaoconfigurationsEntity faPiaoconfigurationsEntity = gson.fromJson(json, FaPiaoconfigurationsEntity.class);
                            if (Constant.Strings.SUC.equals(faPiaoconfigurationsEntity.getCode())) {
                                TipsPop tipsPop = new TipsPop(InvoiceApplicationActivity.this, "开票须知", faPiaoconfigurationsEntity.getBody().getContent());
                                tipsPop.showPopupWindow();
                            }
                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {
                        dismissLoading();
                    }
                });


                break;
            case R.id.tv_confirm: {
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    ToastUtil.initToast(this, "请输入收票人");
                } else if (TextUtils.isEmpty(etPhone.getText().toString())) {
                    ToastUtil.initToast(this, "请输入收票人手机号");

                } else if (TextUtils.isEmpty(etEmail.getText().toString())) {
                    ToastUtil.initToast(this, "请输入收票人邮箱");

                }  else if (TextUtils.isEmpty(etTitle.getText().toString())) {
                    ToastUtil.initToast(this, "请填写公司全称或个人姓名");

                }/* else if (TextUtils.isEmpty(etNum.getText().toString())) {
                    ToastUtil.initToast(this, "请输入纳税人识别号");

                }*/ else if (!imgCheck.isSelected()) {
                    ToastUtil.initToast(this, "请仔细阅读并接受《开票须知》");

                } else {


                    /**
                     * action : integer,1:申请,2:发送到邮箱
                     * orderNo : string,订单号,action=1时必须
                     * type : integer, 发票种类，1: 增值税普通发票,action=1时必须
                     * title : string,发票抬头，当抬头类型为个人时，写死为 个人,action=1时必须
                     * content : string,发票内容,action=1时必须
                     * phone : string,收票人电话号码,action=1时必须
                     * email : string,收票人邮箱,必须
                     * username : string,收票人姓名,action=1时必须
                     * taxpayerNumber : string,纳税人识别号
                     */


                    loadingDialog = LoadingDialog.newInstance("提交中...");
                    loadingDialog.show(getFragmentManager());
                    RadioButton TypeRb = findViewById(rgType.getCheckedRadioButtonId());
                    RadioButton contentRb = findViewById(rgContent.getCheckedRadioButtonId());
                    Orders_invoice orders_invoiceEntity = new Orders_invoice(orderNo, 1,
                            etTitle.getText().toString(), contentRb.getText().toString(),
                            etPhone.getText().toString(), etEmail.getText().toString(),
                            etName.getText().toString(), etNum.getText().toString()
                    );
                    Map<String, Object> stringObjectsHashMap = new HashMap<>();
                    OkHttpUtil.postJson(this, Constant.URL.orders_invoice, orders_invoiceEntity, stringObjectsHashMap, new OkHttpUtil.OnDataListener() {
                        @Override
                        public void onResponse(String url, String json) {
                            dismissLoading();
                            if (!TextUtils.isEmpty(json)) {
                                LogeUtil.e("orders_invoice", json);

                                Orders_invoiceEntity orders_invoiceEntity = gson.fromJson(json, Orders_invoiceEntity.class);
                                if (Constant.Strings.SUC.equals(orders_invoiceEntity.getCode()) && orders_invoiceEntity.getBody().isIsSuccess()) {
                                    if (!TextUtils.isEmpty(etTitle.getText().toString())) {
                                        //保存填的信息
                                        DbFaPiaoTitleUtils.getInstance().insertOrReplace(etTitle.getText().toString(),etNum.getText().toString());

                                    }
                                    ToastUtil.initToast(InvoiceApplicationActivity.this, "提交成功");
                                    onBackPressed();

                                } else {
                                    ToastUtil.initToast(InvoiceApplicationActivity.this, (orders_invoiceEntity.getBody()==null||TextUtils.isEmpty(orders_invoiceEntity.getBody().getMsg())) ? orders_invoiceEntity.getMsg() : orders_invoiceEntity.getBody().getMsg());
                                }

                            }


                        }

                        @Override
                        public void onFailure(String url, String error) {
                            dismissLoading();
                            ToastUtil.initToast(InvoiceApplicationActivity.this, error);

                        }
                    });
                }

            }
            break;
        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private class KeyboardOnGlobalChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {


        private int getScreenHeight() {
            return ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getHeight();
        }

        private int getScreenWidth() {
            return ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getWidth();
        }

        @Override
        public void onGlobalLayout() {
            if (etTitle.hasFocus()) {

                final View decorView = InvoiceApplicationActivity.this.getWindow().getDecorView();

                Rect rect = new Rect();
                // 获取当前页面窗口的显示范围
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                int screenHeight = decorView.getHeight();
                int keyboardHeight = screenHeight - (rect.bottom - rect.top) + ll_title.getHeight(); // 输入法的高度

                boolean preShowing = mIsSoftKeyBoardShowing;
                if (Math.abs(keyboardHeight) > screenHeight / 5) {
                    mIsSoftKeyBoardShowing = true; // 超过屏幕五分之一则表示弹出了输入法
                    /*tipsUseDBPop = new TipsUseDBPop(InvoiceApplicationActivity.this);
                    tipsUseDBPop.showPopupWindow(getScreenWidth(), keyboardHeight);
         */
                } else {
                    if (preShowing) {
                        if (tipsUseDBPop != null) {
                            tipsUseDBPop.dismiss();
                            tipsUseDBPop = null;
                        }
                    }
                    mIsSoftKeyBoardShowing = false;
                }
            }

        }
    }

}
